<template>
  <div>
        <!-- 选择图片 -->
        <input type="file"
               accept="image/*"
               @change="chooseImg" />
        <!-- 预览图片 -->
        <canvas ref="imgPreview"
                height="0"
                width="0"></canvas>
        <!-- 提交图片 -->
        <button @click="uploadImg">提交图片</button>
        <!-- 通过后台返回的url向文件服务器请求图片 -->
       图片预览： <img :src="imgUrlFromServer" width="100" height="100">
        图片地址：{{imgUrlFromServer}}
    </div>

</template>

<script>
// let Base64 = require("js-base64").Base64;
export default {
  data() {
    return {
            imgUrlFromServer: '#',
            base64: ''
    };
  },
  methods: {
     chooseImg (event) {
            let file = event.target.files[0]
            let reader = new FileReader()
            let img = new Image()
            // 读取图片
            reader.readAsDataURL(file)
            // 读取完毕后的操作
            reader.onloadend = (e) => {
                img.src = e.target.result
                // 这里的e.target就是reader
                // console.log(reader.result)
                // reader.result就是图片的base64字符串
                this.base64 = reader.result
            }
            // 预览图片
            let canvas = this.$refs['imgPreview']
            let context = canvas.getContext('2d')
            img.onload = () => {
                img.width = 100
                img.height = 100
                // 设置canvas大小
                canvas.width = 100
                canvas.height = 100
                // 清空canvas
                context.clearRect(0, 0, 100, 100)
                // 画图
                context.drawImage(img, 0, 0, 100, 100)
            }
        },
        uploadImg () {
          // let obj={imgurl:this.base64}
            this.$axios({
              method:'POST',
              url:'http://47.94.4.201/index.php/index/upload/uploadimg',
              data:{
              imgurl:this.base64

              }
            }).then(res => {
                this.imgUrlFromServer = 'http://47.94.4.201'+res.data.data.url
            })
        }

  },
  components: {},
};
</script>

<style scoped></style>
